package com.example.demo.others.git;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.eclipse.jgit.api.Git;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant;

/**
 * Created by Administrator on 2017/3/17 0017.
 */

public class IosTst {

    public static String tagPrefix = "tst_";
    public static String ios_dir = "D:\\company\\ios\\";
    public static String push_dir = "C:\\Users\\Administrator\\Desktop\\tst\\push\\";
    public static String push_crt_dir = "deploy_tst\\";

    public static void run() {

        try {
            GitUtil.pull(GitUtil.xingdu, ios_dir);
            GitUtil.pull(GitUtil.xingdu, push_dir);
            String comment = copy(push_dir + push_crt_dir);
            commit(push_dir, comment);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("ln");
        }

    }

    public static String copy(String target_dir) throws Exception {


        int tag = 0;
        File f = new File(ios_dir + "certs\\prd");
        StringBuilder sb = new StringBuilder("add ios push crts:\n");
        for (File file : f.listFiles()) {
            String oldpath = file.getAbsolutePath();
            String newpathstr = target_dir + file.getName();
            Path newpath = Paths.get(newpathstr);

            System.out.println(file.getName());
            try {

                boolean ex = Files.deleteIfExists(newpath);
                if (!ex) {
                    sb.append(file.getName() + "\n");
                    tag = 1;
                }
            } catch (Exception e) {

            }
            Files.copy(Paths.get(oldpath), newpath);
        }
        System.out.println("ln");


        if (tag == 1)
            return sb.toString();
        return "";
    }


    public static void commit(String dir, String comment) throws Exception {
        if (StringUtils.isBlank(comment))
            return;
        Git git = GitUtil.open(dir);
        GitUtil.commit(git, comment, tagPrefix + DateFormatUtils.format(Instant.now().toEpochMilli(), "yyyyMMdd_HHmm"), comment);
        GitUtil.push(GitUtil.xingdu, git);
        git.close();
    }

}
